package eu.smoothit.sis.admin.backendBean;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import eu.smoothit.sis.admin.backendBean.superclass.DataTableAbstract;
import eu.smoothit.sis.admin.util.DTOComparator;
import eu.smoothit.sis.db.SisDAOFactory;
import eu.smoothit.sis.db.api.daos.ILogEntryDAO;
import eu.smoothit.sis.db.impl.entities.LogEntry;

public class LogBean extends DataTableAbstract<LogEntry> {
	// Properties
	// ---------------------------------------------------------------------------------
	private LogEntry searchExample;
	private List<SelectItem> Allusers;
	private Date selectDate_from;
	private Date selectDate_to;
	// either lastNdays or datepicker
	private String searchMethodTag;

	// define DAO
	private ILogEntryDAO dataDAO = (ILogEntryDAO) SisDAOFactory.getFactory()
			.createLogEntryDAO();

	// initialization
	public LogBean() {
		searchExample = new LogEntry();
		setAllusers(fetchAllUsers());
		actionLoad();
	}

	// getter && setter
	// ----------------------------------------------------------------------------------
	public String getSearchMethodTag() {
		return searchMethodTag;
	}

	public void setSearchMethodTag(String searchMethodTag) {
		this.searchMethodTag = searchMethodTag;
	}

	// Date returned by date picker
	public Date getSelectDate_from() {
		return selectDate_from;
	}

	public void setSelectDate_from(Date selectDateFrom) {
		selectDate_from = selectDateFrom;
	}

	public Date getSelectDate_to() {
		return selectDate_to;
	}

	public void setSelectDate_to(Date selectDateTo) {
		selectDate_to = selectDateTo;
	}

	public List<SelectItem> getAllusers() {
		return Allusers;
	}

	public void setAllusers(List<SelectItem> allusers) {
		Allusers = allusers;
	}

	public LogEntry getSearchExample() {
		return searchExample;
	}

	public void setSearchExample(LogEntry searchExample) {

		this.searchExample = searchExample;
	}

	// Form actions
	// ----------------------------------------------------------------------------------
	@Override
	public void actionSave() {
		// no need for viewer
	}

	@Override
	public void actionDelete() {
		// no need for viewer

	}

	@Override
	public void actionSearch() {
		super.actionSearch();
	}

	@Override
	public void actionLoad() {
		boolean isQuestion = false;

		if (isSearchMode()) {
			LogEntry question = new LogEntry();
			String event = searchExample.getEvent();
			String result = searchExample.getResult();
			String username = searchExample.getUsername();
			if (event.trim().length() != 0) {
				question.setEvent(event);
				isQuestion = true;
			}
			if (result.trim().length() != 0) {
				question.setResult(result);
				isQuestion = true;
			}
			if (username.trim().length() != 0) {
				question.setUsername(username);
				isQuestion = true;
			}
			if (isQuestion) {
				try {
					dataList = dataDAO.get(question);// TODO add part match
					isQuestion = false;
				} catch (Exception e) {
					setErrorMessage(e.getMessage() + " Cause: " + e.getCause());
					e.printStackTrace();
					return;
				}
			} else {
				String message = "Please enter at least one keyword for searching";
				setErrorMessage(message);
			}

			// else: query via date selection calExpectedDate(ActionEvent e)
		} else {
			try {
				dataList = dataDAO.getAll();
			} catch (Exception e) {
				setErrorMessage(e.getMessage() + " Cause: " + e.getCause());
				e.printStackTrace();
				return;
			}
		}

		// Clear selected and editmode rows and sort data.

		// actionSort(null);
		sortByDateDesc();

	}

	public void actionRefresh() {
		searchExample = new LogEntry();
		setAllusers(fetchAllUsers());
		super.actionRefresh();
	}

	public List<SelectItem> fetchAllUsers() {
		List<LogEntry> users;
		List<SelectItem> usersAsSelectItems = new ArrayList<SelectItem>();
		List<String> usersAsSring = new ArrayList<String>();
		users = dataDAO.getAll();
		for (LogEntry u : users) {
			if (!usersAsSring.contains(u.getUsername())) {
				usersAsSring.add(u.getUsername());
				usersAsSelectItems.add(new SelectItem(u.getUsername()));
			}

		}
		return usersAsSelectItems;

	}

	public DateObject dateSelectedByLastNdays(Integer lastNdays) {
		DateObject selectedDate = new DateObject();
		// From is -N days from today
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_YEAR, lastNdays);
		selectedDate.setFrom(c.getTime());
		// To is current day
		selectedDate.setTo(Calendar.getInstance().getTime());
		return selectedDate;
	}

	public Date dateSelectedByDatePicker(String selectedDate) {
		String[] temp = selectedDate.split("-");
		Calendar c = Calendar.getInstance();
		// date format 07-11-2009
		int year = Integer.parseInt(temp[2]);
		int month = Integer.parseInt(temp[1]) - 1;
		int date = Integer.parseInt(temp[0]);
		c.set(year, month, date);
		return c.getTime();
	}

	public void dateSelectionValueChangeListener_from(ValueChangeEvent event) {
		// String selectDateString = (String) event.getNewValue();
		// pass date
		// selectDate_from=dateSelectedByDatePicker();
		// TODO, selectDate_from -> Date type
		selectDate_from = null;
	}

	public void dateSelectionValueChangeListener_to(ValueChangeEvent event) {
		// Date selectDateString = (Date) event.getNewValue();
		// pass date
		// selectDate_to=dateSelectedByDatePicker();
		// TODO, selectDate_from -> Date type

	}

	/**
	 * searching via Date selection
	 */
	public void searchByDate(ActionEvent event) {
		Date from = null;
		Date to = null;
		// TODO enable date picker option later
		searchMethodTag = "lastNdays";
		if (searchMethodTag.equals("lastNdays")) {
			String uiName = "LastNdaysList";
			UIInput ui = (UIInput) event.getComponent().findComponent(uiName);
			Integer LastNdays = Integer.parseInt((String) ui.getValue());
			if (LastNdays == 0) {
				String message = "Last XX days not defined";
				setErrorMessage(message);
			} else {
				DateObject d = dateSelectedByLastNdays(LastNdays);
				from = d.getFrom();
				to = d.getTo();
			}
		} else if (searchMethodTag.equals("datePicker")) {

			from = selectDate_from;
			to = selectDate_to;
		}

		Collection<LogEntry> allRecords = dataDAO.getAll();
		List<LogEntry> queryResult = new ArrayList<LogEntry>();
		for (LogEntry record : allRecords) {
			Date d = record.getDate();
			if (d != null) {
				if (d.after(to) && d.before(from)) {
					queryResult.add(record);
				}
			}
		}
		dataList = queryResult;
		setSearchMode(true);
		actionLoad();
		pageFirst();

	}

	public void sortByDateDesc() {
		// Get and set sort field and sort order.
		String sortFieldAttribute = "date";
		sortField = sortFieldAttribute;
		sortAscending = false;
		Collections.sort(dataList, new DTOComparator(sortField, sortAscending));
		// Clear row modes.
		editModeRows.clear();
		selectedRows.clear();

	}

}

class DateObject {
	private Date from;
	private Date to;

	public Date getFrom() {
		return from;
	}

	public void setFrom(Date from) {
		this.from = from;
	}

	public Date getTo() {
		return to;
	}

	public void setTo(Date to) {
		this.to = to;
	}

}
